<template>
    <div class="environWrapper">
        <Header style="background: var(--left-menu-bgcolor);color: var(--default-color);">
            <div style="display: flex;justify-content: space-between;width: 100%;">
                <div style="color: var(--default-color);font-size:20px;font-weight: 600;">{{this.expeInfo.ecname}}</div>
                <ul class="operation">
                    <li>
                        <Dropdown trigger="click" style="margin-left: 20px" placement="bottom-end">
                            <a href="javascript:void(0)">
                                账号密码
                                <Icon type="ios-arrow-down"></Icon>
                            </a>
                            <DropdownMenu slot="list">
                                <DropdownItem>账号：{{this.userName}}</DropdownItem>
                                <DropdownItem>密码：{{this.pwd}}</DropdownItem>
                            </DropdownMenu>
                        </Dropdown>
                    </li>
                    <li>
                        <Dropdown>
                            <img src="../../assets/exper/vm.png" style="width: 18px;height: 18px;vertical-align: middle" alt="vm">
                            <span style="width:100px;cursor: pointer">{{this.curVmName}}({{this.curAccess}})</span>
                            <Icon type="ios-arrow-down"></Icon>
                            <DropdownMenu slot="list" >
                                <DropdownItem v-for="vm in vmList" :key="vm.id">
                                    <Dropdown placement="right-start" @on-click="getCurVm" id="childMenu">
                                        <DropdownItem :name="vm.id">
                                            <Icon type="md-desktop" style="margin-right:5px"/>
                                            {{vm.name}}
                                            <Icon type="ios-arrow-forward"></Icon>
                                        </DropdownItem>
                                        <DropdownMenu slot="list">
                                            <DropdownItem  v-for="access in vm.accesses" :key="access.accessType" :name="JSON.stringify({vm:vm,access:access})">{{access.accessType}}</DropdownItem>
                                            <!-- <DropdownItem  :name="JSON.stringify({vm:vm,access:{accessType:'console',username:vm.accesses[0].username,password:vm.accesses[0].password}})">console</DropdownItem> -->
                                        </DropdownMenu>
                                    </Dropdown>
                                </DropdownItem>
                            </DropdownMenu>
                        </Dropdown>
                    </li>
                    <li style="cursor: pointer" @click="refreshVm">
                        <img src="../../assets/exper/refresh.png" style="width: 16px;height: 20px;vertical-align: middle;margin-top: -5px" alt="vm">
                        <span>刷新</span>
                    </li>
                    <!--<li style="cursor: pointer">-->
                    <!--<img src="../../assets/expeInfo/fullscreen.png" style="width: 16px;height: 16px;vertical-align: middle" alt="vm">-->
                    <!--<span>{{$t('fullScreen')}}</span>-->
                    <!--</li>-->
                    <li><Divider type="vertical" /></li>
                    <li style="width: 120px">
                        <span style="font-size:26px;color:rgb(51, 115, 255);font-weight: 600">
                        <span style="position: relative;top: 2px;">{{curTime.h}}:{{curTime.m}}:{{curTime.s}}</span>
                    </span>
                    </li>
                </ul>
            </div>
        </Header>
        <Content>
            <div style="display: flex;justify-content: flex-start;width: 100%;height: 100%">
                <div class="left-wrap" >
                    <div class="contrlIcon">
                        <img :src="contrlImg" style="height: 75px;width: 17px" @click="closeLeft">
                    </div>
                    <div class="left-menu">
                        <div class="left-items">
                            <div class="left-item" v-for="(value,index) in leftMenu" :key="index" @click.prevent="clickMenu(index)">
                                <div class="item-text" :class="{textActive:value.type}">{{value.name}}</div>
                                <div class="item-line" :class="{lineActive:value.type}"></div>
                            </div>
                        </div>
                        <Divider style="height: 100%" type="vertical" />
                    </div>
                    <div class="left-content" :style="{width:leftContentWidth}">
                        <div class="exap-data-wrap" :style="{height:leftDataHei}">
                            <div class="exap-data">
                                <div class="main_list">
                                    <div class="exp" data-name="指导书列表" style="display: block;">
                                        <div class="guidancebook" >
                                            <div v-if="expeInfo.customType==1">
                                                 <guideIframe :mdPath="expeInfo.guide" :guideSrc="guideSrc" :contentHeiNei="leftDataHei" :type="1" :fileId="expeInfo.ecid" :fileName="expeInfo.ecname"></guideIframe>
                                            </div>
                                            <div v-else>
                                                <SectionList :data="guideList" :showQuestion="false"></SectionList>
                                                <!-- <div class="exptaskdiv">
                                                <span v-show="!showCloseAndOpenBtn" @click="exptaskexpand">展开</span>
                                                <span v-show="showCloseAndOpenBtn" @click="exptaskclose">关闭</span>
                                                </div>
                                                <div class="guidancebookList">
                                                    <div class="guidancebookdiv" v-for="(value,index) in guideList" :key='index'>
                                                        <div class="guidancebooktitle" :style="{'background-image': `url(${closeSingle})!important`}" @click="guidancebooktitle(index)" data-name="指导书标题">{{value.sectionname}}</div>
                                                        <div class="guidancebookcontent" data-name="指导书内容" style="overflow: hidden; display: block;" v-html="xss(escape2Html(value.sectiontext))"></div>
                                                    </div>
                                                </div> -->
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <iframe :src="curVmUrl" frameborder="0" id="environ" @mouseover="setFocus"></iframe>
            </div>
            <Spin size="large"  fix v-if="spinShow" style="top:60px">
                <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
                <div>试验机正在创建，请稍后...</div>
            </Spin>
        </Content>
        <Modal v-model="closeWindowModal" width="360">
            <p slot="header" style="color:#f60;text-align:center">
                <Icon type="ios-information-circle-outline"></Icon>
                <span>提示</span>
            </p>
            <div style="text-align:center;color:#f60;">
                <h4>课件环境即将销毁</h4>
                <h4>页面将于<span style="font-size:20px;">{{this.closeTime}}</span>秒后关闭</h4>
            </div>
            <div slot="footer"></div>
        </Modal>
        <div style="position:absolute;right:10px;bottom:30px;" v-if="classId"><ChatRoom :classId = "classId" :teacherId="USER_ID" :teacherName="USER_Name"></ChatRoom></div>
    </div>
</template>

<script>
    import $ from 'jquery'
    import cookieUse from '@/libs/cookie.js'
    import encryption from '@/libs/encryption.js'
    import {getTime,geturl,getVms,experimentDetail} from '@/api/selfStudy/courseExp.js'
    import {sectionList_new,donwLoadMdFile} from '@/api/guide.js'
    import webScoket from '@/mixin/webScoket'
    import ChatRoom from '@/components/chatRoom/classChatRoom.vue'
    import guideIframe from '@/view/experimentalScene/designPanel/guideIframe.vue'
    import { escape2Html } from '@/libs/utils'
    import { mapState } from 'vuex';
    import SectionList from '@/components/common/guide-section-list'
    export default {
    	components:{ChatRoom,guideIframe,SectionList},
    	mixins:[webScoket],
        data() {
            return {
            	// USER_ID:'',
            	USER_Name:'',
            	classId:'',
                fullWidth: document.documentElement.clientWidth,
                fullHeight: document.documentElement.clientHeight,
                getToken:'',
                // 本地取数据
                proId:'',
                ecId:'',
                expeInfo:{},
                guideSrc:'',
                // 倒计时
                leftTime:0,
                curTime:{
                    h:'04',
                    m:'00',
                    s:'00'
                },
                vmList:[],
                // 关闭页面
                closeWindowModal:false,
                closeTime:5,  // 关闭页面倒计时
                // 连接
                curVmName:'',
                curAccess:'',
                curVmOsId:'',
                curVmUrl:'',
                curVm:{},
                spinShow:true,
                rem:'16px',
                // 左侧抽屉
                leftMenu:[
                    {
                        name:'指导书',
                        type:true,
                    },
//                    {
//                        name:'问答',
//                        type:false,
//                    },
//                    {
//                        name:this.$t('notes'),
//                        type:false,
//                    },
//                    {
//                        name:this.$t('exercise'),
//                        type:false,
//                    }
                ],
                leftContentWidth:'650px',
                contrlImg:require('../../assets/exper/close-book.png'),
                contrlStatus:true,
                // 说明指导书信息
                guideList:[],
                leftDataHei:'auto',
                // 指导书展开收缩按钮的显示
                showCloseAndOpenBtn:true,
                // 账号密码
                userName:'',
                pwd:'',
                articalContent:'',
            }
        },
        computed: {
            ...mapState('style', {
                
            })
        },
        mounted() {
            // 试验机宽度
            this.getVmsWidth()
            this.leftDataHei = this.fullHeight - 128 + 'px'
            $('.ivu-divider-vertical').css('margin','0px')

            this.getExperData()
            this.getVmList();
            this.getDestoryTime();
            this.destoryInterval = setInterval(() => {
                this.getDestoryTime();
            },1000*60*10)
            this.webSocketStatus();
        },
        created(){
            // 获取用户id
            let November = sessionStorage.getItem('November')
            November = JSON.parse(encryption.SelfUseDecrypt(November))
            this.USER_ID = November.userId
            this.USER_Name = November.userName
            this.classId = this.$route.query.classId
            this.getToken = cookieUse.getCookie('desig-token') || ''
            // 工程id  课件id
            this.proId = this.$route.query.projectId
            this.ecId = this.$route.query.ecid
            this.vmId = sessionStorage.getItem('curVmOsId') || this.$route.query.vmId
            this.accessType = sessionStorage.getItem('accessType') || this.$route.query.accessType
        },
        updated() {
            
        },
        beforeDestory(){
            clearTimeout(this.timeout);
            clearInterval(this.destoryInterval);
        },
        methods: {
            // 获取vms
            getVmList(){
                getVms(this.proId).then(data => {
                    if(data.code == 1){
                        let vms = data.attribute.vms
                        this.vmList = vms;
                        if(vms.length > 0){
                        	if(!this.vmId){
	                            this.curVmName = vms[0].name;
	                            this.userName = vms[0].accesses[0].username;
	                            this.pwd = vms[0].accesses[0].password;
	                            this.curVmOsId = vms[0].id;
	                            this.curAccess = vms[0].accesses[0].accessType;
	                            this.openConsole(this.curAccess,this.curVmOsId);
                            }else{
                              let curVms = vms.filter(vm => vm.id == this.vmId)
                        	  if(curVms.length > 0){
                        	  	this.curVmName = curVms[0].name;
	                            this.userName = curVms[0].accesses[0].username;
	                            this.pwd = curVms[0].accesses[0].password;
	                            this.curVmOsId = curVms[0].id;
	                            this.curAccess = this.accessType;
	                            this.openConsole(this.accessType,this.curVmOsId);
                        	  }else{
                        	  	this.curVmName = vms[0].name;
	                            this.userName = vms[0].accesses[0].username;
	                            this.pwd = vms[0].accesses[0].password;
	                            this.curVmOsId = vms[0].id;
	                            this.curAccess = vms[0].accesses[0].accessType;
	                            this.openConsole(this.curAccess,this.curVmOsId);
                        	  }
                            }
                        }else{
                            this.$Message.error('该工程已被删除或正在重新部署');
                        }
                    }else{
                        this.$Message.error(res.data.message)
                    }
                })
            },
            // 切换试验机
            getCurVm(vmObj){
                var s = vmObj.substr(0,1);
                if(s === '{' ){
                    let vm = JSON.parse(vmObj);
                    this.curVm = vm;
                    this.curVmName = vm.vm.name;
                    this.curVmOsId = vm.vm.id;
                    this.userName = vm.access.username;
                    this.pwd = vm.access.password;
                    this.curAccess = vm.access.accessType;
                    this.openConsole(vm.access.accessType,this.curVmOsId);
                    sessionStorage.setItem('accessType',this.curAccess);
	                sessionStorage.setItem('curVmOsId',this.curVmOsId);
                }
            },
            openConsole(type,vmId){
                let params = {
                    vmId:vmId,
                    type:type,
                    data:{
                        // enableRecordScreen:false
                    }
                }
                geturl(params)
                    .then(data =>  {
                        if(data.code == 1){
                            let url = data.attribute.url;
                            this.curVmUrl = `${url}&Authorization=${this.getToken}`;
                            console.log(this.curVmUrl)
                            this.spinShow = false
                        }else {
                            this.$Message.error({
                                content:data.message,
                                duration:3,
                            })
                            this.spinShow = false
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                        this.spinShow = false
                    })
            },
            // 刷新
            refreshVm(){
                window.location.reload()
            },
            // 获取销毁时间
            getDestoryTime(){
                if(!this.proId){
                    return
                }
                getTime(this.proId)
                    .then(data => {
                        if(data.code === 1){
                            this.leftTime = data.attribute.destroyTime;
                            if(this.leftTime > 0){
                                this.getTimes();
                            }else{
//                                window.close();
                            }
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                    })
            },
            getTimes(){
                clearTimeout(this.timeout);
                let leftTime = this.leftTime;
                if(leftTime > 0){
                    let h = Math.floor(leftTime / 1000 / 60 / 60);
                    let m = Math.floor(leftTime / 1000 / 60 % 60);
                    let s = Math.floor(leftTime / 1000 % 60);
                    this.curTime  = {
                        h:h < 10 ? '0'+h : h,
                        m:m < 10 ? '0'+m : m,
                        s:s < 10 ? '0'+s : s
                    }
                    let _this = this;
                    this.timeout = setTimeout(() => {
                        _this.leftTime = _this.leftTime - 1000;
                        _this.getTimes();
                    },1000);
                }else{
                    // 关闭页面
                    this.closeWindowModal = true;
                    this.timeout = setTimeout(() => {
                        this.closeTime = this.closeTime - 1;
                        if(this.closeTime <= 0){
                            window.close();
                        }
                        this.getTimes();
                    },1000);
                }
            },
            // 左侧信息栏
            clickMenu(index){
                for(let i=0;i<this.leftMenu.length;i++){
                    this.leftMenu[i].type = false
                }
                this.leftMenu[index].type = true
            },
            closeLeft(){
                if(this.contrlStatus){
                    this.contrlImg = require('../../assets/exper/open-book.png')
                    this.leftContentWidth = '0px'
                    $('.left-content').css({
                        padding:'0',
                    })
                    $('.left-menu').css({
                        display:'none'
                    })
                }else {
                    this.contrlImg = require('../../assets/exper/close-book.png')
                    this.leftContentWidth = '650px'
                    $('.left-content').css({
                        padding:'20px 0 20px 20px'
                    })
                    $('.left-menu').css({
                        display:'flex'
                    })
                }
                this.contrlStatus = !this.contrlStatus
                this.getVmsWidth()
            },
            // 试验机宽度
            getVmsWidth(){
                let leftWidth = parseInt(this.leftContentWidth.split('px')[0])  // + 60
                $('#environ').css({
                    width:this.fullWidth - leftWidth +'px'
                })
            },
            // 获取课件详情
            getExperData(){
                let params = {
                    eid:this.ecId,
                    uid:this.USER_ID,
                }
                experimentDetail(params)
                    .then(data=>{
                        if(data.code === 1){
                            // 课件信息
                            this.expeInfo = data.data;
                            if(this.expeInfo.customType==1){
                                this.guideSrc = `/api/minio/filePreview?path=${this.expeInfo.guide}`;
                            }else{
                                 // 指导书
                                this.getGuideFun();
                            }
                           
                        }else {
                            this.$Message.error({
                                content:data.message,
                                duration:3,
                            })
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                    })
            },
            // 课件指导书信息
            getGuideFun(){
                let _this = this
//              let params = {
//                  id:this.expeInfo.guide
//              }
                sectionList_new(this.ecId,this.expeInfo.guide)
                    .then(data=>{
                        if(data.code === 1){
                            this.guideList = data.attribute.datalist
                        }else {
                            this.$Message.error(data.message)
                        }
                        this.addAddressForImg()
                    })
                    .catch(err=>{
                        this.$Message.error(err.message)
                        console.log(err)
                    })
            },
            // 给a标签添加跳转
            addAddressForImg(){
                this.$nextTick(()=>{
                    let $imgs = $('.main_list a')
                    for(let i=0;i<$imgs.length;i++){
                        $imgs[i].target = '_blank'
                    }
                })
            },
            // 鼠标移入时 试验机获取焦点
            setFocus() {
                document.getElementById('environ').contentWindow.focus();
            },
            escape2Html(str) {
            	return escape2Html(str)
			},
            //跳转全屏指导书
            gotoGuideFile(){
                window.openTrain(this.guideSrc,'_blank')
            }
        }
    }
</script>

<style scoped>
    .ivu-layout-content{
        height:calc( 100vh - 60px);
    }
    .ivu-layout-header{
        height: 60px;
        line-height: 60px;
        margin-bottom: 3px;
        background: #fff;
        color:#000;
        overflow: hidden;
        box-shadow: 0 0px 5px 1px #515a6e;
    }
    .ivu-drawer-header{
        display: none;
    }
    .ivu-drawer{
        top:63px!important;
    }
    .operation{
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }
    .operation>li{
        margin-left: 30px;
    }
    #childMenu .ivu-select-dropdown{
        width:100px;
    }
    .environWrapper{
        width: 100%;
        height:100%;
        overflow: hidden;
    }
    .environWrapper .ivu-dropdown-item{
        padding:7px 10px;
        color: var(--main-color);
    }
    /deep/.environWrapper .ivu-dropdown-item:hover {
        background: var(--card-body-bgcolor-1);
    }
    .environWrapper .ivu-layout-header{
        padding: 0 20px 0 20px;
    }
    #environ{
        height: 100%;
        transition: width 1s;
    }
    /*新样式*/
    .left-wrap{
        height: 100%;
        display: flex;
        justify-content: flex-start;
        background-color: var(--drawer-bgcolor);
        position: relative;
        transition: width 1s;
    }
    .left-menu{
        width: 60px;
        display: flex;
        justify-content: space-between;
        transition: width 1s;
    }
    .left-items{
        display: flex;
        justify-content: flex-start;
        flex-direction: column;
        padding-top: 30px;
        width: 58px;
    }
    .left-item{
        padding-left: 15px;
        margin-bottom: 30px;
        cursor: pointer;
    }
    .left-item:after{
        display: block;
        content: '';
        clear: both;
    }
    .item-text{
        writing-mode:vertical-lr;
        color: #333;
        font-weight: 600;
        display: inline-block;
    }
    .textActive{
        color: var(--url-color);
    }
    .item-line{
        width: 4px;
        border-radius: 2px;
        height: 25px;
        background-color: #fff;
        float: right;
    }
    .lineActive{
        background-color: var(--url-color);
    }
    .left-content{
        padding: 20px 0 20px 20px;
        transition: width 1s;
    }
    .contrlIcon{
        position: absolute;
        top: 130px;
        right: -17px;
        cursor: pointer;
        opacity: 0.5;
    }
    .exap-data-wrap{
        width: 100%;
        overflow-x: hidden;
        overflow-y: auto;
    }
    .exap-data{

    }
    .main_list {
        width: 98%;
        /*overflow: hidden;*/
    }
    .main_list .exp {
        width: 100%;
        /*overflow: hidden;*/
        display: none;
    }
    .main_list .exp .guidancebook {
        /*overflow: hidden;*/
        /*margin: 30px 0 0 33px;*/
        /*position: relative;*/
        min-height: 98px;
    }
</style>
